import React, {useCallback, ReactNode} from 'react';
import {Alert, TouchableOpacity, View, Text} from 'react-native';
import {
  launchCamera,
  launchImageLibrary,
  Asset,
} from 'react-native-image-picker';
import FastImage from 'react-native-fast-image';

type ImagePickAndDisplayProps = {
  image: Asset | string | undefined;
  onPickNewImage: (image: any) => void;
};

const ImagePickAndDisplay: React.FC<ImagePickAndDisplayProps> = React.memo(
  props => {
    const onPickNewImage = useCallback(() => {
      Alert.alert('Pick a new image', undefined, [
        {
          text: 'Camera',
          onPress: async () => {
            const asset = await launchCamera({
              mediaType: 'photo',
            });
            if (asset.assets && asset.assets.length > 0) {
              props.onPickNewImage(asset.assets[0]);
            }
          },
        },
        {
          text: 'Album',
          onPress: async () => {
            const asset = await launchImageLibrary({
              mediaType: 'photo',
              selectionLimit: 1,
            });
            if (asset.assets && asset.assets.length > 0) {
              props.onPickNewImage(asset.assets[0]);
            }
          },
        },
        {
          text: 'Cancel',
          style: 'cancel',
        },
      ]);
    }, []);

    let hasImage = Boolean(props.image);
    let imageNode: ReactNode = null;
    if (hasImage) {
      if (typeof props.image === 'string') {
        imageNode = (
          <FastImage
            source={{uri: props.image}}
            className="w-20 aspect-square rounded-lg"
          />
        );
      } else {
        imageNode = (
          <FastImage
            source={{uri: props.image?.uri}}
            className="w-20 aspect-square rounded-lg"
          />
        );
      }
    }

    return (
      <View className="flex-row gap-x-3 flex-wrap">
        {imageNode}
        <TouchableOpacity
          onPress={onPickNewImage}
          className="w-20 h-20 rounded-lg border-1 gap-y-2 justify-center items-center border-[1px] border-dashed border-line1">
          <Text>{hasImage ? '重新上传' : '上传图片'}</Text>
        </TouchableOpacity>
      </View>
    );
  },
);

export default React.memo(ImagePickAndDisplay);
